<template>
  <div class="app-container home">
    <div class="concent">
      <div class="rowbtn">
        <div class="left">
          <!-- 分享按钮 -->
          <div class="sambtn"
               @click="share">
            <img src="@/assets/images/sample/Slice 20@2x.png"
                 alt="" />
            分享
          </div>
          <el-button-group>
            <el-button
              :class="type == 1 ? 'active button' : 'button'"
              @click="typeClick(1, 'PGTA')"
              >PGT-A</el-button
            >
            <el-button
              :class="type == 2 ? 'active button' : 'button'"
              @click="typeClick(2, 'PGTM')"
              >PGT-M</el-button
            >
            <el-button
              :class="type == 3 ? 'active button' : 'button'"
              @click="typeClick(3, 'PGTSR')"
              >PGT-SR</el-button
            >
            <el-button
              :class="type == 4 ? 'active button' : 'button'"
              @click="typeClick(4, 'NICS')"
              >NICS</el-button
            >
          </el-button-group>
        </div>
        <div class="right">
          <div class="searchform">
            <el-input
              v-model="queryParams.searchValue"
              style="width: 200px; margin-right: 20px"
              placeholder="送检单位/受检人/送检单编号"
              clearable
            />
            <el-date-picker
              v-model="time"
              type="daterange"
              range-separator="至"
              start-placeholder="收样开始日期"
              end-placeholder="收样结束日期"
            >
            </el-date-picker>
          </div>
          <el-button type="primary"
                     icon="el-icon-search"
                     size="mini"
                     @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
                     size="mini"
                     @click="resetQuery">重置</el-button>
        </div>
      </div>

      <div class="body">
        <el-col :span="24" :xs="24">
          <el-row :gutter="10" class="mb8">
            <el-col :span="24">
              <div class="toprow">
                <div>
                  <el-tooltip class="item"
                              effect="dark"
                              content="显隐列"
                              placement="top"
                              v-if="checkAlldata">
                    <el-button size="mini"
                               circle
                               icon="el-icon-menu"
                               @click="showColumn" />
                  </el-tooltip>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-table v-loading="loading"
                    :data="itemList"
                    ref="table"
                    width="150px"
                    height="calc(100vh - 330px)"
                    @selection-change="handleSelectionChange"
                    border>
            <el-table-column type="selection"
                             sortable
                             :selectable="handleSelectable">
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-table :data="scope.row.sampleList">
                  <el-table-column v-for="(item, ind) in allData[type].datalist"
                                   :key="ind"
                                   :label="item.label"
                                   :prop="item.prop"
                                   show-overflow-tooltip
                                   align="center"></el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="序号"
                             align="center"
                             type="index"
                             width="80"
                             sortable></el-table-column>
            <el-table-column v-for="(item, ind) in headlist"
                             :key="ind"
                             :label="item.fieldNameCn"
                             :prop="item.fieldName"
                             show-overflow-tooltip
                             width="150px"
                             align="center">
              <template slot-scope="scope">
                <div v-if="item.fieldName == 'patient_name'"
                     :style="getCellColor(scope.row)">
                  {{ scope.row[item.fieldName] }}
                </div>

                <div v-if="item.fieldName != 'patient_name'">
                  {{ scope.row[item.fieldName] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             align="center"
                             class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-edit"
                           @click="handleUpdate(scope.row)"
                           v-hasPermi="['check:item:edit']">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0"
                      :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList" />
        </el-col>
      </div>
    </div>
    <el-dialog title="分享"
               :visible.sync="isOpen">
      <el-form :model="form"
               ref="form"
               :rules="rules">
        <el-form-item label="所属医院"
                      :label-width="formLabelWidth">
          <el-input style="width: 220px"
                    :value="dept.deptName"
                    readonly></el-input>
        </el-form-item>
        <el-form-item label="选择医生"
                      :label-width="formLabelWidth"
                      prop="userId">
          <el-select v-model="form.userId"
                     placeholder="请选择医生">
            <el-option v-for="user in userOptions"
                       :key="user.userId"
                       :label="user.nickName"
                       :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   class="button"
                   @click="shareConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title"
               :visible.sync="open"
               append-to-body>
      <el-transfer :titles="['显示', '隐藏']"
                   v-model="checkdata"
                   :data="checkAlldata"
                   @change="dataChange"
                   ref="transfer">
        <div slot="left">
          <ul>
            <!-- 自定义左侧内容 -->
            <li v-for="item in leftdata"
                :key="item.id">{{item.id}}</li>
          </ul>
        </div>
      </el-transfer>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改   -->
    <el-dialog title="修改信息"
               :visible.sync="isItemOpen">
      <el-form :model="itemForm"
               ref="itemForm"
               :rules="itemRules">
        <el-form-item label="所属医院"
                      :label-width="formLabelWidth">
          <el-input style="width: 220px"
                    :value="itemForm.sjdwName"
                    readonly></el-input>
        </el-form-item>
        <el-form-item label="选择医生"
                      :label-width="formLabelWidth"
                      prop="sharedIds">
          <el-select v-model="itemForm.sjys"
                     placeholder="请选择医生">
            <el-option v-for="user in userOptions"
                       :key="user.nickName"
                       :label="user.nickName"
                       :value="user.nickName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="受检人手机号"
                      prop="patientPhone"
                      :label-width="formLabelWidth">
          <el-input style="width: 220px"
                    v-model="itemForm.patientPhone"
                    placeholder="请输入手机号"
                    maxlength="20" />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   class="button"
                   @click="itemConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import {
  getItemListBySampleDecWay1,
  shareItems,
  updateItem,
} from "@/api/check/item";
import { getAllList, getPagefielduserSava } from "@/api/check/pagefielduser";
import {
  getUserListByDeptId,
  getUserListByDeptName,
} from "@/api/system/custom";
import alldata from "./item1.js";
import moment from "moment";
import { shareSamples } from "@/api/check/sample";


export default {
  name: "Index",
  data () {
    return {
      isItemOpen: false,
      formLabelWidth: "100px",

      time: [],
      type: 1,
      isOpen: false,
      formLabelWidth: "100px",
      form: {},
      // 总条数
      total: 0,
      // 用户表格数据
      itemList: [],

      // 遮罩层
      loading: true,
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sampleDecWay: "PGTA",
        searchValue:""
      },
      status: false,
      allData: [],
      headdata: [],
      user: {},
      dept: {},
      userOptions: [],
      // 表单校验
      rules: {
        userId: [{ required: true, message: "医生不能为空", trigger: "blur" }],
      },

      itemRules: {
        patientPhone: [
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
      },

      open: false,
      title: "隐藏列",
      headlist: [],
      leftdata: [],
      checkdata: [],
      checkAlldata: [],
      activeName: "PGTA",

      itemForm: {
        sjdwName: undefined,
        patientPhone: undefined,
        sjys: undefined,
        id: undefined,
      },
    };
  },

  created () {
    this.allData = alldata;
    this.getAllListData();
    this.getDept();
  },
  mounted () {
    this.allData = alldata;
    if (this.$store.state.user.isRegister == 1) {
      this.headdata = this.allData[this.type].headlist.filter(
        (item) => !item.state
      );
    } else {
      this.headdata = this.allData[this.type].headlist;
    }
  },

  methods: {

    /** 导出按钮操作 */
    handleExport() {
      var sampleDecWay = this.queryParams.sampleDecWay;
      this.download(
        "check/item/export",
        {
          ...this.queryParams,
        },
        sampleDecWay + `_sample_${new Date().getTime()}.xlsx`
      );
    },
    onDragEnd (event) {
      const movedItem = this.leftdata.splice(event.oldIndex, 1)[0];
      this.leftdata.splice(event.newIndex, 0, movedItem);
    },

    getUserList () {
      var that = this;
      var form = {};
      form.deptName = that.itemForm.sjdwName;
      getUserListByDeptName(form).then((response) => {
        if (response.code == "200" && response.data) {
          that.userOptions = response.data;
        }
      });
    },

    itemConfirm: function () {
      var that = this;
      that.$refs["itemForm"].validate((valid) => {
        if (valid) {
          var form = that.itemForm;
          updateItem(form).then((response) => {
            //需要判断当前传入的userId是否有deptId，没有的话提示
            this.$modal.msgSuccess("修改成功");
            this.isItemOpen = false;
            this.getList();
          });
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate (row) {
      this.itemReset();
      const id = row.id || this.ids;
      this.isItemOpen = true;
      this.itemForm.sjdwName = row.sjdw_name;
      this.title = "修改项目信息";
      this.itemForm.id = row.id;
      this.getUserList();
    },

    reset () {
      this.itemForm = undefined;
    },

    itemReset () {
      this.itemForm = {
        sjdwName: undefined,
        patientPhone: undefined,
        nickName: undefined,
        id: undefined,
      };
      this.resetForm("itemForm");
    },

    getCellColor (row) {
      var nickName = this.$store.state.user.nickName;
      if (row.sjys != nickName && row.is_share && row.is_share == 1) {
        return {
          background: "#aa2299",
          color: "#ffffff",
        };
      }
    },

    getPagefielduserSavaData () {
      const arr = [];
      let brr = []
      this.leftdata.forEach(item => {
        brr.push(item.fieldId)
        arr.push({
          id: item.id || null,
          page: item.page,
          type: item.type,
          fieldId: item.fieldId,
          isShow: item.isShow,
        });
      })
      this.checkAlldata.forEach((item) => {
        if (!brr.includes(item.fieldId)) {
          arr.push({
            id: item.id || null,
            page: item.page,
            type: item.type,
            fieldId: item.fieldId,
            isShow: item.isShow,
          });
        }
      });
      getPagefielduserSava(arr).then((res) => {
        this.open = false;
        this.getAllListData();
      });
    },
    submitOk () {
      this.getPagefielduserSavaData();
    },
    // 右侧列表元素变化
    dataChange (data) {
      this.checkAlldata.forEach((item) => {
        if (data.includes(item.key)) {
          item.isShow = "0";
        } else {
          item.isShow = "1";
        }
      });
    },
    // 打开显隐列dialog
    showColumn () {
      this.open = true;
      if (this.open) {
        this.$nextTick(() => {
          var arr = document.getElementsByClassName("el-transfer-panel__list")[0]
          Sortable.create(arr, {
            onEnd: this.onDragEnd
          });
        })
      }

      this.getAllListData(true);
    },
    getAllListData (state) {
      const params = {
        type: this.activeName,
        page: "sampleEnter",
      };
      getAllList(params).then((res) => {
        if (state) {
          const leftdata = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 1
          );
          const rightdata = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 0
          );
          this.leftdata = leftdata
          res.data.forEach((item) => {
            item.key = item.fieldId;
            item.label = item.fieldNameCn;
          });
          this.checkAlldata = res.data.filter(
            (item) => item.type == this.activeName
          );
          const arr = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 0
          );
          const brr = [];
          arr.forEach((item) => {
            brr.push(item.fieldId);
          });
          this.checkdata = brr;
        } else {
          this.headlist = res.data.filter(
            (item) => item.type == this.activeName && item.isShow == 1
          );
          this.getList();
        }
      });
    },
    handleSelectable (row) {
      if (row.sjys == this.$store.state.user.nickName) {
        return true;
      } else {
        return false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //导出操作
    download () { },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.searchValue = undefined;
      this.queryParams.startTime = undefined;
      this.queryParams.endTime = undefined;
      this.time = [];
      this.handleQuery();
    },
    share: function () {
      var that = this;
      var ids = this.ids;
      if (ids == null || ids.length == 0) {
        this.$modal.msgError("请先选择要分享的数据");
        return false;
      } else {
        that.isOpen = true;
      }
    },
    shareConfirm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var userId = this.form.userId;
          var form = {};
          form.sharedId = this.form.userId;
          form.deptId = this.dept.deptId;
          form.ids = this.ids;
          shareItems(form).then((response) => {
            //需要判断当前传入的userId是否有deptId，没有的话提示
            this.$modal.msgSuccess("分享成功");
            this.isOpen = false;
          });
        }
      });
    },
    handleSizeChange (val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    getDept () {
      var that = this;
      var dept = this.$store.state.user.dept;
      if (dept != null || dept != undefined) {
        var deptName = dept.deptName;
        var deptId = dept.deptId;
        that.dept.deptName = deptName;
        that.dept.deptId = deptId;
        that.getUser(deptId);
      }
    },
    getUser (deptId) {
      var that = this;
      var form = {};
      form.deptId = deptId;
      that.user.nickName = this.$store.state.user.nickName;
      var userId = this.$store.state.user.userId;
      form.userId = userId;
      that.user.userId = userId;
      getUserListByDeptId(form).then((response) => {
        if (response.code == "200" && response.data) {
          that.userOptions = response.data;
        }
      });
    },
    handleCurrentChange (val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    /** 查询列表 */
    getList () {
      this.loading = true;
      if (this.time && this.time.length > 0) {
        var startTime = moment(this.time[0]).format("YYYY-MM-DD");
        var endTime = moment(this.time[1]).format("YYYY-MM-DD");
        this.queryParams.startTime = startTime;
        this.queryParams.endTime = endTime;
      }

      getItemListBySampleDecWay1(this.queryParams).then((response) => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    typeClick (id, sampleDecWay) {
      this.type = id;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.sampleDecWay = sampleDecWay;
      this.activeName = sampleDecWay;
      if (this.$store.state.user.isRegister) {
        this.headdata = this.allData[id].headlist.filter((item) => !item.state);
      } else {
        this.headdata = this.allData[id].headlist;
      }
      this.getAllListData();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      var that = this;
      that.ids = selection.map((item) => item.id);
      that.single = selection.length != 1;
      that.multiple = !selection.length;
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  height: calc(100% - 50px);
  // background: #f2f3f4;
  .concent {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #ffffff;
    border-radius: 6px 6px 6px 6px;
    opacity: 1;
    box-sizing: border-box;
    padding: 10px 20px;

    .toprow {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      box-sizing: border-box;
      h2 {
        font-weight: bold;
        color: #1f2329;
        font-size: 20px;
        margin: 10px 0 18px 0 !important;
      }
    }
  }
  .rowbtn {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      display: flex;
      .sambtn {
        width: 84px;
        height: 32px;
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid #d0d3d6;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 13px;
        cursor: pointer;
        img {
          width: 16px;
          height: 16px;
          margin-right: 10px;
        }
      }
      .button {
        height: 34px;
        background: #efefef;
        color: #595959;
        cursor: pointer;
      }
      .button:hover {
        background: #aa2299;
        color: #ffffff;
      }
      .active {
        background: #aa2299;
        color: #ffffff;
      }
    }
    .right {
      // width: 400px;
      height: 34px;
      display: flex;
      .search {
        background: #aa2299;
        color: #ffffff;
        margin-left: 10px;
      }
      .reset {
        background: none;
        color: #1f2329;
      }
    }
  }
  .searchform {
    // margin: 10px 0;
  }

  ::v-deep.is-checked {
    .el-checkbox__inner {
      border-color: #aa2290;
      background: #aa2290;
    }
  }
  ::v-deep.el-input.is-focus .el-input__inner {
    border-color: #aa2290 !important;
    box-shadow: 0 0 3px #aa2290 !important;
  }
  ::v-deep.el-card {
    border: none;
  }
  .body {
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 10px;
  }
  .pagefy {
    position: fixed;
    bottom: 20px;
    right: 0;
    color: #1f2329;
  }
  ::v-deep.el-icon-arrow-down {
    font-size: 20px;
  }
  ::v-deep.el-icon-arrow-up {
    font-size: 20px;
  }

  ::v-deep.el-table {
    .el-table__body-wrapper {
      height: calc(100vh - 330px) !important;
    }
  }
}
</style>
